import { Node } from '../core/node.js';
import { Material } from '../core/material.js';
import { UrlTexture } from '../core/texture.js';

class SpriteMaterial extends Material {
    constructor(texture) {
        super();

        this.defineSampler("u_image", texture);
    }

    get name() {
        return "sprite";
    }

    get vertexSource() {
        return `
            attribute vec3 a_position;
            attribute vec2 a_texCoord;

            varying vec2 v_texCoord;

            vec4 vertex_main(mat4 proj, mat4 view, mat4 model) {
                v_texCoord = a_texCoord;

                return proj * view * model * vec4(a_position, 1.0);
            }
        `;
    }

    get fragmentSource() {
        return `
            uniform sampler2D u_image;

            varying vec2 v_texCoord;

            vec4 fragment_main() {
                return texture2D(u_image, v_texCoord);
            }
        `;
    }
}

export class Sprite extends Node {
    constructor(options) {
        super();

        this._uv = options.uv;

        let texture = options.url ? new UrlTexture(options.url) : options.texture;

        this.material = new SpriteMaterial(texture);
    }

    onRendererChanged(renderer) {
        let positionData = [
            -1.0, -1.0, 0.0,
            1.0, -1.0, 0.0,
            1.0, 1.0, 0.0,
            -1.0, 1.0, 0.0
        ];

        let texCoordData = this._uv || [
            0, 1,
            1, 1,
            1, 0,
            0, 0
        ]

        let indexData = [
            0, 1, 2,
            0, 2, 3,
        ];

        let attributes = [
            renderer.createRenderAttribute("a_position", 3, positionData),
            renderer.createRenderAttribute("a_texCoord", 2, texCoordData),
        ];

        let drawInfo = renderer.createRenderDrawInfo(indexData.length, indexData);

        this._renderObject = renderer.createRenderObject(drawInfo, attributes, this.material, this);
    }

    //换图
    updateTexture(texture) {
        if (this._renderer) {
            this._renderer.updateRenderTexture(this._renderObject.samplers[0].renderTexture, texture);
        }
    }
}